import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:healthy_station_flutter/provider/provider_app.dart';
import 'package:healthy_station_flutter/utils/res_images.dart';

import '../../entity/diag_and_presciption_entity.dart';
import '../../entity/drugs_entity.dart';
import '../../entity/pay_wait_entity.dart';
import '../../nav/nav_route.dart';
import '../../network/XHttp.dart';
import '../../network/api.dart';
import '../../utils/constants.dart';
import '../../utils/log_utils.dart';
import '../../utils/res_colors.dart';
import '../../utils/res_strings.dart';
import '../../utils/screen_adapter.dart';
import '../../widget/DialogController.dart';
import '../../widget/title_bar.dart';
import '../../widget/title_bar_sub.dart';

/// 
/// @Description 
/// @Author WuJianFeng
/// @Date 2024/3/21 11:36
/// 

class PayWait extends StatefulWidget{
  const PayWait({super.key});

  @override
  State<StatefulWidget> createState() => _PayWaitState();
  
}

class _PayWaitState extends State<PayWait> with SingleTickerProviderStateMixin{
  /// 会重复播放的控制器
  late final AnimationController _controller;

  @override
  void initState() {
    anim();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }


  void anim(){
    _controller = AnimationController(duration: const Duration(seconds: 2), vsync: this)
      ..repeat();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: ImageUtils.getImageProvider("gradient_bg.webp"),
                fit: BoxFit.fill,
                alignment: Alignment.bottomCenter
            )
        ),
        child: Column(
          children: [
            /// 标题
            const TitleBarWidget(),
            /// 副标题
            TitleBarSub(sTitlePayWait),
            ///内容
            Expanded(
              child: Container(
                alignment: Alignment.center,
                width: MediaQuery.of(context).size.width,
                margin: EdgeInsets.all(Adapt.pt(24)),
                decoration: BoxDecoration(
                    //背景色
                    color: Colors.transparent,
                    //border
                    border: Border.all(color: Colors.white, width: Adapt.pt(4)),
                    //圆角
                    borderRadius: BorderRadius.circular(Adapt.pt(10))
                ),
                child: FutureBuilder<List<DrugsEntity>?>(
                    future: prescriptionQueryV2(),
                    builder: (context, AsyncSnapshot<List<DrugsEntity>?> snapshot) {
                      return (snapshot.data != null && snapshot.data!.isNotEmpty) ?
                      Container(
                        padding: EdgeInsets.all(Adapt.pt(24)),
                        child: ListView.builder(
                          itemCount: snapshot.data?.length,
                          itemBuilder: (context, index) {
                            return waitPayItem(snapshot.data?[index].doctor,snapshot.data?[index].createTime,snapshot.data?[index].consultId);
                          },
                        ),
                      ) : const Text(sDataNull);
                    }),
              ),
            ),


          ],
        ),
      ),
    );
  }

  Widget waitPayItem(String? doctorName, String? prescriptionTime, String? consultId){
    return Container(
      decoration: BoxDecoration(
          //背景色
          color: Colors.white,
          //圆角
          borderRadius: BorderRadius.circular(Adapt.pt(8))
      ),
      margin: EdgeInsets.only(bottom: Adapt.pt(24)),
      padding: EdgeInsets.all(Adapt.pt(24)),
      width: Adapt.pt(1824),
      height: Adapt.pt(184),
      child: Stack(
        children: [
          /// 所属机构
          Positioned(
            child: Align(
              alignment: Alignment.topLeft,
              child: Text(
                "$sAffiliation${AppInfo().stationName}",
                style: TextStyle(color: color_1e3d5b, fontSize: Adapt.pt(32), fontWeight: FontWeight.bold)),
            ),
          ),
          ///医生姓名
          Positioned(
            top: Adapt.pt(60),
            child: Align(
              alignment: Alignment.centerLeft,
              child: RichText(
                text: TextSpan(
                    text: sDoctorName,
                    style: TextStyle(fontSize: Adapt.pt(28), color: color_1e3d5b),
                    children: [
                      TextSpan(
                          text: "$doctorName",
                          style: TextStyle(
                              fontSize: Adapt.pt(28),
                              color: color_384c60))
                    ]
                ),
              ),
            ),
          ),
          ///开方时间
          Positioned(
            child: Align(
              alignment: Alignment.bottomLeft,
              child: RichText(
                text: TextSpan(
                    text: sPrescriptionTime,
                    style: TextStyle(fontSize: Adapt.pt(28), color: color_1e3d5b),
                    children: [
                      TextSpan(
                          text: "$prescriptionTime",
                          style: TextStyle(
                              fontSize: Adapt.pt(28),
                              color: color_384c60))
                    ]
                ),
              ),
            ),
          ),
          ///缴费按钮
          Positioned(
            child: Align(
              alignment: Alignment.bottomRight,
              child: InkWell(
                onTap: (){
                  var progressValue = 0.1.obs;

                  var timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
                    LogUtils.d("__progressValue:$progressValue");
                    progressValue.value = progressValue.value + 0.1;
                    if(progressValue >= 0.9){
                      timer.cancel();
                    }
                  });

                  DialogController.instance.show(
                      context,
                      Obx(() {
                        return dialogContent(progressValue.value);
                      }), (dialogState){
                        if(!dialogState){
                          timer.cancel();
                        }
                      });
                  queryDiagAndPresciption();
                },
                child: Container(
                  decoration:  BoxDecoration(
                    gradient:  const LinearGradient(
                      begin: FractionalOffset.topCenter,
                      end: FractionalOffset.bottomCenter,
                      colors: [
                        color_97c3fe,
                        color_3a7afe,
                      ],
                    ),
                    borderRadius:  BorderRadius.circular(Adapt.pt(8)),
                  ),
                  alignment: Alignment.center,
                  width: Adapt.pt(200),
                  height: Adapt.pt(72),
                  child: Text(sPayTheFees, style: TextStyle(fontSize: Adapt.pt(32), color: Colors.white, fontWeight: FontWeight.bold)),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<List<DrugsEntity>?> prescriptionQueryV2() async {

    XHttp.getInstance().post<PayWaitEntity>(Api.prescriptionQueryV2, {
      "idCard": Constant.cardNumber,
      "cardType": Constant.cardType,
      "machineId": AppInfo().machineId,
    }).then((value){

      return value;

    }).catchError((err) {
      LogUtils.d("__prescriptionQueryV2-err ${err}");
      return null;
    });

  }

  void queryDiagAndPresciption(){

    XHttp.getInstance().post<DiagAndPresciptionEntity>(Api.queryDiagAndPresciption, {
      "consultId": Constant.consultId,
    }).then((value){
      Navigator.of(context).pop();
      Navigator.pushNamed(context, routerOneClickConsult, arguments: value);

    }).catchError((err) {
      LogUtils.d("__prescriptionQueryV2-err ${err}");
      return null;
    });
  }

  Widget dialogContent(double progressValue){
    return Container(
      decoration: BoxDecoration(
        //背景色
          color: Colors.white,
          //圆角
          borderRadius: BorderRadius.circular(Adapt.pt(8))
      ),
      width: Adapt.pt(945),
      height: Adapt.pt(596),
      child:Stack(
        children: [
          /// 关闭按钮
          Positioned(
            child: Align(
              alignment: Alignment.topRight,
              child: InkWell(
                onTap: (){
                  DialogController.instance.hide(context);
                },
                child: SizedBox(
                  width: Adapt.pt(143),
                  height: Adapt.pt(143),
                  child: ImageUtils.getImgWithSize("close_grey.webp",47,47),
                ),
              ),
            ),
          ),
          /// 加载圈
          Positioned.fill(
            top: Adapt.pt(144),
            child: Align(
              alignment: Alignment.topCenter,
              child:RotationTransition(turns: _controller, child: Image.asset("assets/images/icon_loading_blue.webp")),
            ),
          ),
          /// 提示文字
          Positioned.fill(
            top: Adapt.pt(366),
            child: Align(
              alignment: Alignment.topCenter,
              child: Text(sPrescriptQueryTip, style: TextStyle(color: color_273d58, fontSize: Adapt.pt(30))),
            ),
          ),
          /// 进度条
          Positioned.fill(
            top: Adapt.pt(446),
            child: Align(
              alignment: Alignment.topCenter,
              child: SizedBox(
                width: Adapt.pt(464),
                height: Adapt.pt(16),
                child: LinearProgressIndicator(
                  backgroundColor: color_eaf1ff,
                  color: color_4583fd,
                  value: progressValue, // 设置进度值，范围为0.0到1.0
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
 
 